package com.java.fileman;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

public class BasicAuth {
	
	private static Properties prop = new Properties();
	private Logger log;
	public BasicAuth(String appDir) throws FileNotFoundException, IOException{
		prop.load(new FileInputStream(appDir+File.separator+"WEB-INF"+File.separator+"users.properties"));
		log = Logger.getLogger(BasicAuth.class);
		log.debug("BasicAuth()");
	}
	
	public AuthToken authenticate(String username, String password) throws Exception{
		log.debug("authenticate()");
		String user = prop.getProperty(username);
		log.debug("user : "+user);
		if(user != null && !user.equals("")){
			String[] userInfo = user.split(":");
			if(userInfo.length != 4){
				log.debug("user list file is not correctly formatted , 4 attr expected for"+username);
				throw new Exception("user list file is not correctly formatted , 4 attr expected for"+username);
			}else{
				
				if(userInfo[0].equals(password)){
					
					AuthToken authToken = new AuthToken();
					authToken.setEmail(userInfo[2]);
					authToken.setName(userInfo[3]);
					authToken.setGroup(userInfo[1]);
					authToken.setUsername(username);
					return authToken;
				}
				return null;
			}
		}
		return null;
	}
}
